package com.jinhua.config;

import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 高性能Bean复制工具类
 *
 *  * NOTE:
 *  * ===============================================================
 *  * - 基于（同名属性）的复制
 *  * - 属于浅复制
 *  * - 同名不同类型的属性，不会复制（即使存在继承关系或是装拆箱类）e.g. int->Integer
 *  * - 同集合类不同泛型，可以复制，后续取出元素时会报类型转换错误，如果后续只是做比如json序列化，不会影响 e.g. List<Double> -> List<BigDecimal>
 *  * - 集合类型为引用复制，浅拷贝
 *  * ===============================================================
 * @author WuHuang
 * @date 2022/8/25
 */
public class BeanCopierUtil {

    private static final ConcurrentMap<String, BeanCopier> bcCache = new ConcurrentHashMap<>();
    private static final String keySplitor = "->";
    private static final ConcurrentMap<String, Constructor> constCache = new ConcurrentHashMap<>();

    /**
     * 对象复制
     *
     * @param srcObject  源对象
     * @param destObject 目标对象
     * @param converter  自定义转换器
     * @param <S>
     * @param <D>
     */
    public static <S, D> void copy(S srcObject, D destObject, Converter converter) {
        if (Objects.isNull(srcObject) || Objects.isNull(destObject)) {
            return;
        }
        BeanCopier bc = getBeanCopier(srcObject.getClass(), destObject.getClass());
        bc.copy(srcObject, destObject, converter);
    }

    /**
     * 对象复制
     *
     * @param srcObject  源对象
     * @param destObject 目标对象
     * @param <S>
     * @param <D>
     */
    public static <S, D> void copy(S srcObject, D destObject) {
        if (Objects.isNull(srcObject) || Objects.isNull(destObject)) {
            return;
        }
        BeanCopier bc = getBeanCopier(srcObject.getClass(), destObject.getClass());
        bc.copy(srcObject, destObject, null);
    }

    public static <S, D> D copy(S srcObject, Class<D> destClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        if(Objects.isNull(srcObject)){
            return null;
        }
        Class<?> srcClass = srcObject.getClass();
        BeanCopier bc = getBeanCopier(srcClass, destClass);
        Constructor<D> constructor = getConstructor(destClass);
        D d = constructor.newInstance();
        bc.copy(srcObject, d, null);
        return d;
    }

    public static <S, D> List<D> copyList(List<S> srcList, Class<S> srcClass, Class<D> destClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        List<D> destList = new ArrayList<>();
        BeanCopier bc = getBeanCopier(srcClass, destClass);
        Constructor<D> constructor = getConstructor(destClass);
        for (S s : srcList) {
            D d = constructor.newInstance();
            destList.add(d);
            if (s == null || d == null) {
                continue;
            }
            bc.copy(s, d, null);
        }
        return destList;
    }

    public static <S, D> List<D> asyncCopyList(List<S> srcList, Class<S> srcClass, Class<D> destClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        List<D> destList = new ArrayList<>();
        BeanCopier bc = getBeanCopier(srcClass, destClass);

        Constructor<D> constructor = getConstructor(destClass);

        srcList.parallelStream().forEachOrdered(s -> {
            D d = null;
            try {
                d = constructor.newInstance();
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            destList.add(d);
            if (s == null || d == null) {
                return;
            }
            bc.copy(s, d, null);
        });
        return destList;
    }


    public static <S, D> void copyList(List<S> srcList, List<D> destList, int srcOffset, int destOffset, int len) {
        if (srcList == null || destList == null || srcList.isEmpty() || destList.isEmpty()) {
            throw new IllegalArgumentException("srcList and destList required not empty.");
        }
        if (srcOffset < 0 || destOffset < 0) {
            throw new IllegalArgumentException("srcOffset and destOffset required >=0.");
        }
        if (len < 1) {
            throw new IllegalArgumentException("len required >0.");
        }
        int srcSize = srcList.size();
        int destSize = destList.size();
        if (srcSize < srcOffset + len || destSize < destOffset + len) {
            throw new IllegalArgumentException("srcOffset+len and destOffset+len required not out of range.");
        }
        Class<?> srcClass = srcList.get(srcOffset).getClass();
        Class<?> destClass = destList.get(destOffset).getClass();
        BeanCopier bc = getBeanCopier(srcClass, destClass);

        for (int i = 0; i < len; i++) {
            bc.copy(srcList.get(srcOffset + i), destList.get(destOffset + i), null);
        }
    }

    private static <D> Constructor<D> getConstructor(Class<D> destClass) {
        return constCache.computeIfAbsent(destClass.getName(), key -> {
            try {
                return destClass.getConstructor();
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        });
    }

    private static BeanCopier getBeanCopier(Class<?> srcClass, Class<?> destClass) {
        String key = generateKey(srcClass, destClass);
        BeanCopier bc = bcCache.computeIfAbsent(key, k -> {
            return BeanCopier.create(srcClass, destClass, false);
        });
        return bc;
    }

    private static String generateKey(Class<?> srcClass, Class<?> destClass) {
        StringBuilder sb = new StringBuilder("");
        String srcClassName = srcClass.getName();
        String destClassName = destClass.getName();
        sb.append(srcClassName).append(keySplitor).append(destClassName);
        return sb.toString();
    }
}
